<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="600px"
    title="申请配送商"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="140"
      :inline="true"
      size="small"
    >
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="配送商名称"
            prop="distributeName"
          >
            <el-input
              v-model="formData.distributeName"
              clearable
              placeholder="请输入配送商名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="企业所在地区"
            prop="area"
          >
            <el-cascader
              ref="cascader"
              v-model="formData.area"
              :popper-append-to-body="false"
              style="width: 100%;"
              :options="citys"
              placeholder="请选择企业所在地区"
              :props="{ expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
              clearable
              @change="areaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="详细地址"
            prop="address"
          >
            <el-input
              v-model="formData.address"
              clearable
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="配送产品"
            prop="productId"
            style="width: 100%;"
          >
            <el-row>
              <div style="width: 100%;">
                <el-select
                  v-model="formData.productId"
                  style="width: 100%;"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  :remote-method="proRemoteMethod"
                  :loading="proLoading"
                  value-key="id"
                  placeholder="请选择产品"
                  @change="selectProChange"
                >
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="getProductName(item)"
                    :value="item.id"
                  >
                    <div class="pro-item">
                      <span>{{ getProductName(item) }}</span>
                    </div>
                  </el-option>
                </el-select>
              </div>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="配送地区"
            prop="distributeArea"
            style="width: 100%"
          >
            <el-cascader
              ref="disCascader"
              v-model="formData.distributeArea"
              :popper-append-to-body="false"
              style="width: 100%;"
              :options="citys"
              placeholder="请选择配送地区"
              :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
              collapse-tags
              clearable
              @change="distributeAreaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="联系人"
            prop="contactsName"
          >
            <el-input
              v-model="formData.contactsName"
              clearable
              placeholder="请输入联系人姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="联系人电话"
            prop="contactsPhone"
          >
            <el-input
              v-model="formData.contactsPhone"
              clearable
              placeholder="请输入手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="width: 100%;"
            label="其他信息"
            prop="otherInfo"
          >
            <el-input
              v-model="formData.otherInfo"
              clearable
              placeholder="请输入其他信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import area from '@/utils/area.js'
import {validateVETel} from '@/utils/validate'

export default defineComponent({
  name: 'DistributorApply',
  emits: ['refresh'],
  setup(props, context) {
    const api = inject('api')
    const formRef = ref(null)
    const currentInstance = getCurrentInstance()
    const citys = area
    const cascader = ref(null)
    const disCascader = ref(null)
    var datas = reactive({
      proLoading: false,
      formData: {
        distributeName: '',
        area: [],
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        address: '',
        productId: '',
        contactsName: '',
        contactsPhone: '',
        region: [],
      },
      productOptions: [],
    })
    const validateTel = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        if (validateVETel(value)) {
          callback(new Error('手机号格式不正确'))
        } else {
          callback()
        }
      }
    }
    var formRules = reactive({
      distributeName: [
        { required: true, message: '请输入配送商名称', trigger: 'blur' },
      ],
      area: [
        { required: true, message: '请选择企业所在地区', trigger: 'change' },
      ],
      address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
      productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
      contactsPhone: [
        {
          required: false,
          validator: validateTel,
          trigger: 'blur',
        },
      ],
    })
    var formLabelWidth = ref(100)
    var dialogShow = ref(false)
    const open = (productId) => {
      dialogShow.value = true
      formRef.value.clearValidate()
    }
    const close = () => {
      formRef.value.resetFields()
      dialogShow.value = false
    }
    const proRemoteMethod = async(query) => {
      if (query !== '') {
        datas.proLoading = true
        var pro = await api.common.GET_PRODUCT_LIST({ keyWord: query })
        if (pro.code === 0) {
          datas.productOptions = pro.data.list
        } else {
          datas.productOptions = []
        }
        datas.proLoading = false
      } else {
        datas.productOptions = []
      }
    }
    const selectProChange = (id) => {
      var item = datas.productOptions.find((p) => p.id)
      if (item) {
        datas.currentSelect = item
      }
    }
    const areaChange = (val) => {
      if (val && val.length) {
        datas.formData.provinceCode = val[0]
        datas.formData.cityCode = val[1]
        datas.formData.areaCode = val[2]
      } else {
        datas.formData.provinceCode = ''
        datas.formData.cityCode = ''
        datas.formData.areaCode = ''
      }
    }
    const distributeAreaChange = (val) => {
      console.log(val)
      datas.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        disCascader.value.getCheckedNodes()
      )
    }
    const create = () => {
      api.distributors
        .DISTRIBUTORS_APPLAY_CREATE(datas.formData)
        .then((res) => {
          if (res.code === 0) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '创建成功',
            })
            close()
            context.emit('refresh')
          }
        })
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          create()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      ...toRefs(datas),
      formRef,
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      selectProChange,
      proRemoteMethod,
      citys,
      cascader,
      disCascader,
      areaChange,
      distributeAreaChange,
    }
  },
})
</script>
